<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-tabs type="border-card" style="height: 85vh;">
        <el-tab-pane label="基本信息" style="margin-bottom: 100px;">
          <el-row>
            <el-col :span="12">
              <el-form-item label="商品编号" prop="number">
                <el-input v-model="form.number" placeholder="请输入商品编号"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入商品名称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="零售价" prop="retailPrice">
                <el-input v-model="form.retailPrice" placeholder="请输入商品零售价(保留小数点后两位)"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="进货价" prop="buyingPrice">
                <el-input v-model="form.buyingPrice" placeholder="请输入商品进货价(保留小数点后两位)" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="主图logo" prop="logo">
                <ImageUpload v-model="form.logo"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio v-for="item in statusOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

        </el-tab-pane>
<!--        <el-tab-pane label="编辑图片">-->
<!--          <el-row>-->
<!--            <el-col :span="24">-->
<!--              <el-form-item label="主图logo" prop="logo">-->
<!--                <ImageUpload v-model="form.logo"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->

<!--          <el-form-item label="类型" prop="mediaType">-->
<!--            <el-radio-group v-model="form.mediaType">-->
<!--              <el-radio v-for="item in typeList" :label="item.dictValue">{{ item.dictLabel }}</el-radio>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->

<!--          <el-form-item label="图文" prop="content" v-if="form.mediaType == '0'">-->
<!--            <el-upload-->
<!--              class="avatar-uploader"-->
<!--              :action="url"-->
<!--              :before-upload="checkUpload"-->
<!--              :on-success="uploadSuccess"-->
<!--              :on-remove="handleRemove"-->
<!--              :limit="5"-->
<!--              :headers="headers"-->
<!--              list-type="picture-card"-->
<!--              multiple-->
<!--              :file-list="fileList"-->
<!--            >-->
<!--              <i class="el-icon-plus avatar-uploader-icon"></i>-->
<!--            </el-upload>-->
<!--          </el-form-item>-->

<!--          <el-form-item label="视频" prop="mediaPath" v-if="form.mediaType == '1'">-->
<!--            <el-upload-->
<!--              class="avatar-uploader"-->
<!--              :action="base_url + '/common/upload/media'"-->
<!--              :before-upload="checkUpload2"-->
<!--              :on-success="handleSuccess"-->
<!--              :on-remove="beforeRemove"-->
<!--              :on-exceed="handleExceed"-->
<!--              :limit="1"-->
<!--              :headers="headers"-->
<!--              list-type="picture-card"-->
<!--              :multiple="multiple"-->
<!--              :file-list="fileMediaList"-->
<!--              accept=".mp4,.3gp.m3u8">-->

<!--              <div slot="file" slot-scope="{file}">-->
<!--                <video :src="base_url+form.mediaPath" style="width: 100px;height: 100px"></video>-->
<!--                <span class="el-upload-list__item-actions">-->
<!--                  <span-->
<!--                    class="el-upload-list__item-preview"-->
<!--                    @click="handlePictureCardPreview(file)"-->
<!--                  >-->
<!--                    <i class="el-icon-zoom-in"></i>-->
<!--                  </span>-->
<!--                  <span-->
<!--                    class="el-upload-list__item-delete"-->
<!--                    @click="beforeRemove(file)"-->
<!--                  >-->
<!--                    <i class="el-icon-delete"></i>-->
<!--                  </span>-->
<!--                </span>-->
<!--              </div>-->
<!--              <i slot="default" class="el-icon-plus avatar-uploader-icon"></i>-->
<!--            </el-upload>-->
<!--            <el-dialog :visible.sync="dialogVisible" style="align-items: center">-->
<!--              <video style="height: 500px;width: 100%;" controls="controls" :src="base_url + form.mediaPath"></video>-->
<!--            </el-dialog>-->
<!--          </el-form-item>-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="商品详情">-->
<!--          <div style="height: 72vh;overflow-y: auto;">-->
<!--            <el-row>-->
<!--              <el-col :span="24">-->
<!--                <el-form-item label="详情" prop="details">-->
<!--                  <vue-ueditor-wrap v-model="form.details" :config="myConfig"></vue-ueditor-wrap>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
<!--            </el-row>-->
<!--&lt;!&ndash;            <el-row>&ndash;&gt;-->
<!--&lt;!&ndash;              <el-col :span="24">&ndash;&gt;-->
<!--&lt;!&ndash;                <el-form-item label="商品售后" prop="services">&ndash;&gt;-->
<!--&lt;!&ndash;                  <vue-ueditor-wrap v-model="form.services" :config="myConfig"></vue-ueditor-wrap>&ndash;&gt;-->
<!--&lt;!&ndash;                </el-form-item>&ndash;&gt;-->
<!--&lt;!&ndash;              </el-col>&ndash;&gt;-->
<!--&lt;!&ndash;            </el-row>&ndash;&gt;-->
<!--          </div>-->

<!--        </el-tab-pane>-->
      </el-tabs>


      <el-form-item size="large" style="position: absolute; bottom: 15px; left: -25px;">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import VueUeditorWrap from "vue-ueditor-wrap";
import ImageUpload from '@/components/ImageUpload';
import { listLibrary, getLibrary, delLibrary, addLibrary, updateLibrary, exportLibrary } from "@/api/mall/library";

export default {
  components: {
    VueUeditorWrap, ImageUpload
  },
  data() {
    return {
      appendToBody: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: false,
      // 总条数
      total: 0,
      // 课程id
      courseId: undefined,
      // 状态字典
      statusOptions: [{
        dictLabel: "启用",
        dictValue: "1"
      }, {
        dictLabel: "禁用",
        dictValue: "0"
      }],
      // 媒体类型字典
      typeList: [{
        dictLabel: "图片集",
        dictValue: "0"
      },{
        dictLabel: "视频",
        dictValue: "1"
      }],
      routerOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        number: undefined,
        typeId: undefined,
        name: undefined,
        sold: undefined,
        logo: undefined,
        details: undefined,
        services: undefined,
        wxClientId: undefined,
        retailPrice: undefined,
        buyingPrice: undefined,
        mediaType: '0',
        mediaPath: undefined,
        specsType: undefined,
        status: "1",
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      },
      // 表单校验
      rules: {
        number: [
          {required: true, message: "商品编码不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "商品名称不能为空", trigger: "blur"}
        ],
        buyingPrice: [
          {
            required: false,
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确的金额格式',
            trigger: 'blur'
          }
        ],
        retailPrice: [{
          required: false,
          pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入正确的金额格式',
          trigger: 'blur'
        }]
      },
      base_url: process.env.VUE_APP_BASE_API,
      //文件列
      fileList: [],
      // 视频列
      fileMediaList: [],
      // 设置上传的请求头部
      headers: {Authorization: "Bearer " + getToken()},
      //上传地址
      url: process.env.VUE_APP_BASE_API + "/common/upload",
      //是否禁用上传
      flag: false,
      //图片路径
      files: {path: ''},
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 540,
        // 初始容器宽度
        initialFrameWidth: '100%',
        //启用自动保存
        enableAutoSave: true,
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！部署在国外的服务器，如果无法访问，请自备梯子）
        serverUrl: process.env.VUE_APP_BASE_API + '/api/ueditor/controller?userId=' + this.$store.getters.userInfo.userId,
        // serverUrl:'http://35.201.165.105:8000/controller.php',
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: this.getBaseUrl() + '/ueditor/',
        zIndex: 1
      },
      dialogImageUrl: '',
      dialogVisible: false
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_router").then(response => {
      this.routerOptions = response.data;
    });
  },
  methods: {
    getList() {
      this.loading = true;
      this.form.id = this.$route.query.id;
      if (this.form.id != "" && this.form.id != undefined && this.form.id != null) {
        getLibrary(this.form.id).then(res => {
          this.form = res.data;
          if (res.data.mediaPath) {
            var response = {
              fileName: res.data.mediaPath
            }
            this.fileMediaList.push({ url: this.base_url + res.data.mediaPath, response });
          }
        })
      }
      this.loading = false;
    },
    // 状态字典翻译
    stateFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 页面路由字典翻译
    routerFormat(row, column) {
      return this.selectDictLabel(this.routerOptions, row);
    },

    resetForm() {
      this.$refs['form'].resetFields();
      this.fileList = [];
      this.form.mediaType = '0';
      this.form.status = '1';
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateLibrary(this.form).then(response => {
              if (response.code == 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.$store.dispatch("tagsView/delView", this.$route);
                var location = this.routerFormat("Library/list");
                // var location = '/mall/shopping/library/list';
                this.$router.push({'path': location, name: 'Library/list', 'query': {}})
              }
            })
          } else {
            addLibrary(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.$store.dispatch("tagsView/delView", this.$route);
                var location = this.routerFormat("Library/list");
                // var location = '/mall/shopping/library/list';
                this.$router.push({'path': location, name: 'Library/list', 'query': {}})
              }
            })
          }
        }
      });
    },

    /** 上传之前的校验 */
    checkUpload(file) {
      // console.log("文件类型", file)
      const imgType = file.type
      //图片不大于2M
      const isLtSize = file.size / 1024 / 1024 < 2
      if (['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].indexOf(imgType) === -1) {
        this.$message.error('上传图片只能是 JPG、PNG、GIF格式!')
        return false;
      }
      if (!isLtSize) {
        this.$message.error(`上传图片大小不能超过2MB!`)
        return false;
      }
    },
    /** 上传成功后的回调 */
    uploadSuccess(response, file, fileList) {
      this.setFilePaths(fileList)
      this.flag = true
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.setFilePaths(fileList)
    },
    setFilePaths(fileList) {
      var array = []
      // console.log(fileList)
      fileList.forEach(e => {
        if(e.response) {
          array.push(e.response.fileName)
        }else if(e.res){
          array.push(e.res.fileName)
        }
      })
      if (array.length > 0) {
        this.form.pics = array.join(',')
      }
      this.fileList = fileList
    },

    handleSuccess(file, fileMediaList) {
      // console.log('上传成功', file, fileMediaList)
      if (typeof fileMediaList == "array") {
        fileMediaList.filter(e => {
          e.url = e.response.url;
          e.fileName = e.response.fileName;
          this.form.mediaPath = e.response.fileName;
        })
        this.fileMediaList = fileMediaList;
      } else {
        fileMediaList.url = fileMediaList.response.url;
        fileMediaList.fileName = fileMediaList.response.fileName;
        this.fileMediaList = [fileMediaList];
        this.form.mediaPath = fileMediaList.response.fileName;
      }
    },
    beforeRemove(file, fileMediaList) {
      if (this.isXsYc) {
        return;
      }
      // console.log('移除', file, fileMediaList);
      this.$message({
        type: 'success',
        message: '移除成功!'
      });
      this.fileMediaList = [];
      this.form.mediaPath = undefined;
      return;
    },
    handleExceed(e) {
      // console.log(e)
      this.$message({
        message: '请先删除已有文件后，再进行上传',
        type: 'error'
      });
    },
    checkUpload2(file) {
      // console.log("文件类型", file)
      //视频不能大于100m
      const isLtSize = file.size / 1024 / 1024 < 100
      if (!isLtSize) {
        this.$message.error(`上传视频不能大于100m!`)
        this.isXsYc = true;
        return false;
      }
    },
    handlePictureCardPreview(file) {
      // console.log(file);
      this.dialogVisible = true;
    }
  }

}
</script>

<style scoped>
.dialogClass {
  top: 2vh;
}

.el-upload-list__item {
  width: 100px !important;
  height: 100px !important;
}

.avatar-uploader i {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader i:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
